package helixoide.secondlife.devices;

import helixoide.hxLog;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
/*
 * This will be used to send stuff to second life via a queueing system. 
 * not entirely sure of the specifics but i am thinking there will be an array list that stores the messages.
 *  each device w
 */
public class messageQueue 
{
	private ArrayList<String> msgQueue = new ArrayList<String>();
	private URL deviceURL;
	private double time;
	private double lastTime;
	private Timer timer;
	private boolean canCancel;
	public String implode(String[] list,String sep)
	{
		String toReturn = "";
		for(int i = 0;i<list.length;i++)
		{
			if(i==0)
			{
				toReturn += list[i];
			}
			else
			{
				toReturn += (sep + list[i]);
			}
		}
		return toReturn;
	}
	public messageQueue(URL deviceURL)
	{
		this.deviceURL = deviceURL;
	}
	public void updateURL(String url)
	{
		
		hxLog.write("Message Queue", "Message Queue with URL " +this.deviceURL.toString()+ " is trying to update the url\n");
		try
		{
			this.deviceURL = new URL(url);
		}
		catch(MalformedURLException e)
		{
			e.printStackTrace();
			System.out.println("uhoh can't set the new URL damnit\n");
			hxLog.write("Message Queue", "Unable to Set new URL in MessageQueue");
		}
	}
	public void addMsg(String msg)
	{
		
		hxLog.write("Message Queue", "adding Message to queue: " + msg);
		lastTime = time;
		timer = new Timer();
		time = (int)(System.currentTimeMillis() / 1000);
		if(time-lastTime<=2.0 && lastTime!=0)
		{
			try
			{
				if(canCancel)
				{
					timer.cancel();
					canCancel = false;
				}
			}
			catch(IllegalStateException e)
			{
				//do nothing this error is pointless and i need to avoid it
			}
			msgQueue.add(msg);
			try
			{
				timer.schedule((new timed(this,this.msgQueue)),0, (long)(1.5 * 1000));
				this.canCancel = true;
			}
			catch(IllegalStateException e)
			{
				//i fucking hate these errors, but I have no idea how to stop them
			}
			
		}
		if(msgQueue.size()==4)
		{
			try
			{
				if(canCancel)
				{
					timer.cancel();
					canCancel = false;
				}
			}
			catch(IllegalStateException e)
			{
				//do nothing this error is pointless and i need to avoid it
			}
			String[] messages = null;
			this.msgQueue.toArray(messages);
			String buffer = "queued<<" + implode(messages,":*:");
			this.msgDevice(buffer);
		}
		if(time-lastTime>2.0 || lastTime == 0.0)
		{
			try
			{
				if(canCancel)
				{
					timer.cancel();
					canCancel = false;
				}
			}
			catch(IllegalStateException e)
			{
				//do nothing this error is pointless and i need to avoid it
			}
			if(msgQueue.size()!=0)
			{
				if(msgQueue.size()==1)
				{
					String buffer = "non-queued<<" + msgQueue.get(0);
					this.msgDevice(buffer);
				}
				else
				{
					String[] messages = null;
					this.msgQueue.toArray(messages);
					String buffer = "queued<<" + implode(messages,":*:");
					this.msgDevice(buffer);
				}
			}
			if(msgQueue.size()==0)
			{
				String buffer = "non-queued<<" + msg;
				this.msgDevice(buffer);
			}
			this.msgQueue.clear();
		}
	}
	private String msgDevice(String msg)//used internally for communicating to the device
	{
		String toReturn = "";//this is used to store the complete page that we retrieve
		hxLog.write("Message Queue", "Sending Message from queue: " + msg);
		try
		{
			URL objURL = this.deviceURL;
			URLConnection conn = objURL.openConnection();
			conn.setDoOutput(true);
			OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
			out.write(msg);
			out.flush();
			//
			BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while((line = in.readLine()) != null)
			{
				toReturn += line + "\n";
			}
			out.close();
			in.close();
		}
		catch(Exception e)
		{
			e.printStackTrace();
			hxLog.write("Message Queue", "Error Communicating with Device via http");
		}
		return toReturn;
	}
	public class timed extends TimerTask
	{
		
		private messageQueue msgQueue;
		private ArrayList<String> theQueue;
		public timed(messageQueue theQueue, ArrayList<String> list)
		{
			this.msgQueue = theQueue;
			this.theQueue = list;
		}
		public void run()
		{
			try
			{
				if(canCancel)
				{
					timer.cancel();
					canCancel = false;
				}
			}
			catch(IllegalStateException e)
			{
				//do nothing this error is pointless and I just need to avoid it
			}		
			if(theQueue.size()!=0)
	        {
	            if(theQueue.size()==1)
	            {
	                String buffer = "non-queued<<" + this.theQueue.get(0);
	                this.msgQueue.msgDevice(buffer);
	            }
	            else
	            {
	            	String[] messages = null;
					this.theQueue.toArray(messages);
					String buffer = "queued<<" + implode(messages,":*:");
	                this.msgQueue.msgDevice(buffer);
	            }
	            this.theQueue.clear();
	        }
			
			
		}
	}
}
